﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Mangix.Core;
using Mangix.Services.SysLog;
using Mangix.Admin.Framework;
using Mangix.Services.SysDomain;
using Mangix.Mapping.SysDomain;
using System.Web.Http;
using Mangix.Admin.Framework.Menu.Register;

namespace Mangix.Admin
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            MvcHandler.DisableMvcResponseHeader = true;
            //
            EngineContext.Initialize(new MangixEngine());

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AreaRegistration.RegisterAllAreas();

            //
            GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            EngineContext.Current.Resolve<IRegisterApplicationService>().initRegister();
            try
            {
                var logger = EngineContext.Current.Resolve<ISysLogService>();
                logger.Information("Admin 系统启动", null);
            }
            catch (Exception)
            {

            }
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }
        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (Request.Url.AbsolutePath.Equals("/"))
            {
                var _sysDomainService = EngineContext.Current.Resolve<ISysDomainService>();
                var domainList = _sysDomainService.getAllCache();
                if (domainList == null || !domainList.Any())
                    return;
                string host = Request.Url.Host;
                var domain = domainList.FirstOrDefault(o => o.Domain.Equals(host, StringComparison.InvariantCultureIgnoreCase));
                if (domain == null)
                    return;
                if (Request.HttpMethod.Equals("POST", StringComparison.InvariantCultureIgnoreCase))
                    return;
                switch (domain.DomainType)
                {
                    case (int)EnumDomainType.移动端:
                        this.Context.RewritePath("~/mobile");
                        break;
                    case (int)EnumDomainType.APP接口:
                        this.Context.RewritePath("~/app");
                        break;
                }
            }

        }

        protected void Application_EndRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_Error(Object sender, EventArgs e)
        {
            var exception = Server.GetLastError();
            logException(exception);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="exc"></param>
        protected void logException(Exception exc)
        {
            if (exc == null)
                return;

            var httpException = exc as HttpException;
            if (httpException != null && httpException.GetHttpCode() == 404)
                return;

            try
            {
                var logger = EngineContext.Current.Resolve<ISysLogService>();
                logger.Error(exc.Message, exc);
            }
            catch (Exception)
            {
                log4net.LogManager.GetLogger("global").Error(exc);
            }
        }
    }
}
